<?php

class ContractsController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */


    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Contracts();
        if (isset($_POST)) {

            $model->attributes = $_POST;
            if (isset($_POST['contractstartdate'])) {
                $dateExp = explode('-', $_POST['contractstartdate']);
                if ($dateExp[0] == 2011 || $dateExp[0] == 2012) {
                    $counter = $dateExp[0] . '-contract';
                    $model->contractid = $dateExp[0] . '-' . Counters::model()->getNextNumber($dateExp[0] . '-contract');

                } else {
                    $counter = 'contract';
                    $model->contractid = date('Y') . '-' . Counters::model()->getNextNumber('contract');

                }
            } else {
                $counter = 'contract';
                $model->contractid = date('Y') . '-' . Counters::model()->getNextNumber('contract');

            }
            if ($model->save()) {
                Counters::model()->saveNumber($counter);
                echo json_encode(array(
                    'success' => true,
                    'msg' => "Saving successful",
                    'contractid' => $model->contractid
                ));
            } else {
                echo json_encode(array(
                    'success' => false,
                    'errors' => $model->getErrors()
                ));
            }
        }

        Yii::app()->end();
    }
    protected function getScheduleDateFromPost($post){
        $rs=array();
        
        
        if(is_array($post)){
            $i=0;
            foreach($post as $item){                
                
                if(stripos($item['name'], '-date')!==false){
                    $rs[++$i]=$item['value'];
                }
            }
        }        
        return $rs;
    }
    public function reprocessFormParam($array){
        $rs=array();
        foreach($array as $key=>$value){
            
            $p1=strripos($key, '[')+1;
            $p2=strripos($key,']');
            if($p2-$p1>0){
                $key=substr($key, $p1,$p2-$p1);                
                $rs[$key]=$value;
            }else if($p2==false && $p1>0){
                $key=substr($key, $p1);                
                $rs[$key]=$value;
            }                      
        }
        return $rs;
    }
    
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    
    public function actionUpdate($contractid)
    {

        $model = $this->loadModel($contractid);
        $contacts = CHtml::listData(Locationcontacts::model()->findAll("locno='$model->locno' and custno='$model->custno'"),'contact','email');
        if(empty($contacts)) $contacts = array('N/A','N/A');
        outputJsByList($contacts, 'contacts');
        if ($model != NULL && isset($_POST['form'])) {
            $data= (($this->reprocessFormParam($_POST['form'])));         
            $model->attributes = $data;
            $model->contractamount=$this->getContractAmount($model->contractid);
            echo $model->billtype;
            $this->addCItem($contractid,$model);
            if($model->billtype==Contracts::TYPE_QUARTERLY){
                $model->saveQuarterlyPayment();
            }else if($model->billtype==Contracts::TYPE_MONTHLY){
                $model->saveMonthlyPayment();
            }
            
            if ($model->save()) {
                $this->showAjaxMessage('Save successful',true);
                
            }
        }
        $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $model->custno,
            'locno' => $model->locno
        ));
        $customer = Customers::model()->findByPk($model->custno);
        outputJsByList(Warehouse::model()->getList(), 'warehouse');

        $contractLedger = ContractLedger::model()->findAll('contractid=:contractid', array('contractid' => $contractid));
        $planTypes = Plantypes::model()->findAll();
        $rs = array();
        foreach ($planTypes as $i => $item) {
            $rs[$i]['key'] = $item->id;
            $rs[$i]['value'] = $item->plantype;
        }
        Yii::app()->clientScript->registerScript('planTypes', "var planTypesData=" . json_encode($rs), CClientScript::POS_HEAD);
	$criteria = new CDbCriteria();
        $criteria->order = 'sort ASC';	  
	$serviceLevelList = FlOptions::model()->findAll($criteria);
        $rs = array();
        foreach ($serviceLevelList as $i => $item) {
            $rs[$i]['key'] = $item->id;
            $rs[$i]['value'] = $item->description;
        }
        Yii::app()->clientScript->registerScript('fl', "var serviceLevelData=" . json_encode($rs), CClientScript::POS_HEAD);

        $itemsList = array();
        foreach ($contractLedger as $i => $item) {
            $itemsList[] = $item->attributes;
            $itemsList[$i]['price'] = $item->price;

            $itemsList[$i]['noprinttext'] = $item->getYesNoValue($item->noprint);
            $itemsList[$i]['taxedtext'] = $item->getYesNoValue($item->taxed);
        }
        Yii::app()->clientScript->registerScript('itemlist', "var contractLedgerList=" . json_encode($itemsList), CClientScript::POS_HEAD);
        $list = ContractNotes::model()->findAll('contractid=:contractid', array('contractid' => $model->contractid));
        $rs = array();
        foreach ($list as $item) {
            $rs[] = $item->attributes;
        }
        Yii::app()->clientScript->registerScript('contractNoteData', "var contractNoteData=" . json_encode($rs), CClientScript::POS_HEAD);
        //post the tax to javascript
        $tax=Taxcode::model()->find('zipcode=:zipcode',array(
            'zipcode'=>$model->location->zip
        ));
        if($tax==NULL){
            throw new CHttpException(500,'Please update zipcode in '
                    .CHtml::link('Location',$this->createUrl('/locations/update', array('custno'=>$model->custno,'locno'=>$model->locno))));
        }
        $tax=CJSON::encode($tax->attributes);
        Yii::app()->clientScript->registerScript('tax',"
                var TAX_EXEMPT_YES=".Locations::TAX_EXEMPT_YES.";
                var TAX_EXEMPT_NO=".Locations::TAX_EXEMPT_NO.";
                var tax=$tax;
                var isExempt={$model->location->isexempt};
                ",  CClientScript::POS_HEAD);
        
        $list = ContractEquipment::model()->findAll('contractid=:contractid', array('contractid' => $model->contractid));
        $rs = array();
        foreach ($list as $i=>$item) {
            $rs[$i] = $item->attributes;
            $original = Equipment::model()->findByPk($item->equipmentid);
            if(isset($original))
	    $rs[$i]['description'] = $original->description;
        }
        Yii::app()->clientScript->registerScript('ContractEquipmentData', "var ContractEquipmentData=" . json_encode($rs), CClientScript::POS_HEAD);

        if (isset($_POST['Contracts'])) {
            $model->attributes = $_POST['Contracts'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->contractid));
        }

        $this->render('update', array(
            'model' => $model,
            'location' => $location,
            'customer' => $customer
        ));
    }


    public function actionSaveBatchItems()
    {
        if (isset($_POST['contractid']) && isset($_POST['data'])) {
            $contractid = $_POST['contractid'];
            $data = $_POST['data'];


            //$data=json_decode($_POST['data']);
            //echo json_encode($data);
            foreach ($data as $item) {
                if (isset($item[0]) && $item[0] == 'delete') {
                    $num = Yii::app()->db->createCommand()->delete('tbl_contract_ledger', 'contractid=:contractid AND id=:id', array(
                        'contractid' => $_POST['contractid'],
                        'id' => $item[1]
                    ));
                    if ($num == 0)
                        echo "Delete failed at {$item[1]}";
                } else {

                    if (isset($item['id']) && $item['id'] != 0) {

                        $model = ContractLedger::model()->findByPk(intval($item['id']));

                        $model->warehouse = $item['warehouse'];
                        $model->partno = $item['partno'];
                        $model->description = $item['description'];
                        $model->qty = $item['qty'];
                        $model->price = $item['price'];
                        $model->taxed = $item['taxed'];
                        $model->noprint = $item['noprint'];
                        $model->cost = $item['cost'];
                        $model->markupvalue = $item['markupvalue'];

                        if ($model->save() === false) {
                            echo "Update failed: " . json_encode($model->getErrors());
                        }
                    } else {
                        $model = new ContractLedger;
                        //$model->attributes=$item;
                        $model->contractid = $contractid;
                        $model->warehouse = $item['warehouse'];
                        $model->partno = $item['partno'];
                        $model->description = $item['description'];
                        $model->qty = $item['qty'];
                        $model->price = $item['price'];
                        $model->taxed = $item['taxed'];
                        $model->noprint = $item['noprint'];
                        $model->cost = $item['cost'];
                        $model->markupvalue = $item['markupvalue'];
                        if ($model->save() === false) {
                            echo "Create failed: " . json_encode($model->getErrors());
                        }
                    }
                }
            }
        }
    }
    public function actionGetContractAmount($contractid){
        $sum=$this->getContractAmount($contractid);
        if($sum!==false){
            echo $sum;
        }
        echo 0;
    }
    public function getContractAmount($contractid){
        $sum=Yii::app()->db->createCommand('select sum(price*qty) from tbl_contract_equipment where contractid=:contractid')
                ->bindValues(array('contractid'=>$contractid))->queryScalar();
        return $sum;
    }
    public function actionSaveBatchNotes()
    {
        if (isset($_POST['contractid']) && isset($_POST['data'])) {
            $contractid = $_POST['contractid'];
            $data = $_POST['data'];
            foreach ($data as $item) {
                if (isset($item[0]) && $item[0] == 'delete') {
                    Yii::app()->db->createCommand()->delete('tbl_contract_notes', 'contractid=:contractid AND id=:id', array(
                        'contractid' => $contractid,
                        'id' => $item[1],
                    ));
                } else {
                    $model = NULL;
                    if (isset($item['id']) && $item['id'] != 0) {

                        $model = ContractNotes::model()->findByPk($item['id']);
                        if ($model != NULL) {
                            $model->dateofnote = $item['dateofnote'];
                            $model->note = $item['note'];
                            //$model->jobid=$item['jobid'];
                        }
                    } else {
                        $model = new ContractNotes;
                        $model->dateofnote = $item['dateofnote'];
                        $model->note = $item['note'];
                        $model->contractid = $item['contractid'];
                    }
                    if ($model != NULL) {
                        $model->dateofnote = $item['dateofnote'];
                        $model->note = $item['note'];
                        if ($model->save()) {
                            echo 'Save successful';
                        } else {
                            echo json_encode($model->getErrors());
                        }
                    }
                }
            }
        }
    }

    public function actionDelete($contractid)
    {
        $model = $this->loadModel($contractid);
        $custno = $model->custno;
        $locno = $model->locno;
        var_dump($model->delete());
        ContractLedger::model()->deleteAll('contractid=:contractid', array('contractid' => $contractid));
        ContractNotes::model()->deleteAll('contractid=:contractid', array('contractid' => $contractid));

    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionCancel($contractid)
    {
        /* @var $model Contracts */

        $model = $this->loadModel($contractid);
        $custno = $model->custno;
        $locno = $model->locno;
        //$model->delete();
        //ContractLedger::model()->deleteAll('contractid=:contractid', array('contractid' => $contractid));
        //ContractNotes::model()->deleteAll('contractid=:contractid', array('contractid' => $contractid));
        $this->redirect(array('/contracts', 'custno' => $custno, 'locno' => $locno));
    }

    /**
     * Lists all models.
     */
    public function actionIndex($custno, $locno)
    {
        $jobs = new Jobs();
        $jobs->custno = $custno;
        $jobs->locno = $locno;
        $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
            'custno' => $custno,
            'locno' => $locno
        ));
        $customer = Customers::model()->findByPk($custno);
        if ($location == NULL) throw new CHttpException ('Your request page can not found', 404);

        //adding some javascript variable;
        //jsVariableGen('Locations', 'id', array('locname','add1','city','state'), 'locations', 'custno=:custno',array('custno'=>$custno),' | ');
        outputJsByList($jobs->getBillToList(), 'locations');

        outputJsByList(SalesDepartments::model()->getListData(), 'departments');

        outputJsByList(Employees::model()->getEmployeeList(), 'employees');
        outputJsByList(Employees::model()->getSalePersonList(), 'sale');

        outputJsByList(ContractType::getListData(), 'billingstatus');


        outputJsVarible($customer->salesperson, 'defaultSalesPerson');


        //get note list

        $this->render('index', array(
            'location' => $location,
            'jobs' => $jobs
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Contracts('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Contracts']))
            $model->attributes = $_GET['Contracts'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     * @return  @var $model Contracts
     */
    public function loadModel($id)
    {
        $model = Contracts::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionList($custno, $locno, $page = 0, $sort = NULL)
    {
        $data = CHtml::listData(ContractStatus::model()->findAll('inactive=0'), 'id', 'description');


        if ($page > 0) $page--;
        $order = CJSON::decode($sort);

        $data = new CActiveDataProvider('Contracts', array(
            'criteria' => array(
                'condition' => 'custno=:custno AND locno=:locno',
                'params' => array(
                    'custno' => $custno,
                    'locno' => $locno,
                ),
                'order' => isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL
            ),
            'pagination' => array(
                'pageSize' => 20,
                'currentPage' => $page
            )
        ));
        $typeList = CHtml::listData(ContractType::model()->findAll(), 'id', 'description');
        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {

                $rs['data'][$i] = $item->getAttributes();
                $rs['data'][$i]['statusText'] = $item->StatusText;
                if (isset($typeList[$item->contractype]))
                    $rs['data'][$i]['typeText'] = $typeList[$item->contractype];
                else {
                    $rs['data'][$i]['typeText'] = 'Service';
                }
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'contracts-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    
    public function actionPageList(){
        $this->render('pagelist');
    }
    public function getListAllData($query=NULL,$page=NULL,$sort=NULL){
        
        $crit=new CDbCriteria();
        if($sort!=NULL){
            $order=CJSON::decode($sort);
            $crit->order=$order[0]['property'].' '.$order[0]['direction'];
        }else{
            $crit->order='CAST( SUBSTR( contractid, 1,LOCATE(  "-", contractid )-1  ) AS SIGNED) ,CAST( SUBSTR( contractid, LOCATE(  "-", contractid ) +1 ) AS SIGNED )';
        }
        if($query!=NULL){
            $crit->alias='c';
            $crit->join='left join tbl_contract_type ct on ct.id= c.contractype
                         left join tbl_contract_status cs on cs.id= c.status
                         left join tbl_locations l on l.locno = c.locno and l.custno=c.custno
                         
                ';
            $crit->compare('l.locname', $query,true);
            $crit->compare('l.state', $query,false,'or');
            $crit->compare('l.zip', $query,false,'or');
            $crit->compare('l.state', $query,false,'or');
            $crit->compare('ct.description', $query,true,'or');
            $crit->compare('cs.description', $query,true,'or');
            $crit->compare('c.contractstartdate', $query,false,'or');
            $crit->compare('c.contractid', $query,false,'or');
        }
        $pagination=new CPagination;
        if($page > 0) $page--;
        if($page>=0){
            $pagination->setCurrentPage($page);
            $pagination->setPageSize(20);
        }else{
            $pagination->setCurrentPage($page);
            $pagination->setPageSize(999999999); // ìninite!!!!!!!
        }
        $list= new CActiveDataProvider('Contracts',array(
            'criteria'=>$crit,
            'pagination'=>$pagination
        ));
        $rs=array();
        if($list!=NULL && $list->getTotalItemCount()>0){
            
            $rs['totalCount']=$list->getTotalItemCount();
            foreach($list->getData() as $i=>$item){
                $rs['data'][$i]=$item->attributes;
                $rs['data'][$i]['statusText']=$item->getStatusText();
                $rs['data'][$i]['contracttypeText']=  ContractType::getText($item->contractype);
                $location=$item->location;
                if($location!=NULL){
                    $rs['data'][$i]['locname']=$location->locname;
                    $rs['data'][$i]['csz']=$location->city.' '.$location->state.' '.$location->zip;
                }else{
                    $rs['data'][$i]['locname']='';
                    $rs['data'][$i]['csz']='';
                }
            }
            
        }
        return $rs;
    }
    public function actionListAll($query=NULL,$page=0,$sort=NULL){
        echo CJSON::encode($this->getListAllData($query, $page, $sort));
    }
    public function actionContractReport(){
        $data=$this->getListAllData(NULL,-1);
        $this->render('contractreport',array(
            'data'=>$data
        ));
    }
    
    public function addCItem($contractid,&$contract=null){
        
        if($contract==NULL){
            $contract=Contracts::model()->findByPk($contractid);
        }
        if($contract!=NULL){
            
            $partno='C-'.ContractType::getText($contract->contractype);
            $inv= Inventory::model()->findByPk($partno);
            $pricecode=Yii::app()->db->createCommand('select pricecode from tbl_customers where custno=:custno')
                    ->bindValues(array('custno'=>$contract->custno))->queryScalar();
            if($inv!=NULL){
                Yii::app()->db->createCommand()->delete('tbl_contract_ledger', 'contractid=:contractid AND partno!=:partno', array(
                    'contractid'=>$contractid,
                    'partno'=>$partno
                ));
                $model=ContractLedger::model()->find('contractid=:contractid AND partno=:partno',array(
                    'partno'=>$partno,
                    'contractid'=>$contractid
                ));
                
                if($model==NULL){
                    $model=new ContractLedger();
                    $model->partno=$partno;
                    $model->contractid=$contractid;
                    $model->description=$inv->description;
                    $model->qty=1;
                    $model->cost=0;
                    $model->markupvalue=190;
                    $model->taxed=0;
                    $model->noprint=0;
                    $model->tax1=0;
                    
                }
                $model->price=$inv->getPrice($pricecode);
                $model->price+=$this->getContractAmount($contractid);
                
                if($model->save()){
                    return true;
                }
            }
            
        }
        return false;
        
        
    }
}
